module.exports = function(app, passport){

    var API_LOCK_TIME = 5 * 60 * 1000;

    // prepare passport api authentication
    var LocalStrategy = require('passport-local').Strategy;

    passport.use('api-local-login', new LocalStrategy({
        usernameField     : 'email',
        passwordField     : 'password',
    }, function(email, password, done) {

      var regex = new RegExp(["^", email, "$"].join(""), "i");
      Domain.User.findOne({'local.email': regex}, function(err, user) {
         if (err || !user) { return done(err, null);
         } else if (Date.now() < user.locked_until) {
            return done(null, false);
         } else if (!user.validPassword(password)) {  
            if (user.login_attempts < MAX_LOGIN_ATTEMPTS) {
               Domain.User.update({_id: user._id}, {$inc: {login_attempts: 1}}, function(err, num) {
                  return done(null, false);
               });
            } else {
               Domain.User.update({_id: user._id}, {login_attempts: 1, locked_until: Date.now() + API_LOCK_TIME}, function(err, num) {
                   return done(null, false);
               });
            }
         } else {
            var token = user.generateHash(user._id + Date.now());
            Domain.User.update({_id: user._id}, {login_attempts : 1, rememberme: token}, function(err, num) {
               if (err) return done(null, false);
               else     {
                   user.rememberme = token;
                   return done(null, user);
               }
            });
         }});
 
    }));


    // if authorised, req.user will be assigned
    // otherwise return json : {error: 'Unauthorized'}
    var requireApiAuthenticate = function(req, res, next) {
       var token = req.body.token; 
       if (token) {
           Domain.User.findOne({rememberme: token}, function(err, user) {
               if (err) return res.json({error: 'cannot access db'})
               if (!user) return res.json({error : 'Unauthorized'});

               req.user = user;
               next();
           });
       } else
           return res.json({ error: 'Unauthorized'});
    }



   // ajax RESTful service
   app.route('/ajax')
      .get(function(req, res){
         res.send({value: JSON.stringify(req.body) });
      })
      .post(function(req, res){
         res.send({value: JSON.stringify(req.body) });
      })
      .put(function(req, res){
         res.send({value: JSON.stringify(req.body) });
      })
      .delete(function(req, res){
         res.send({value: JSON.stringify(req.body) });
      });


    // curl -H "Content-Type: application/json" 
    //      -d '{"token": "$2a$08$9YVYiwtDcW8UBEzdOhgIROkucQxQQgjQ6i2z2eMrrpjjopSLR6ZCC"}' 
    //          http://localhost/api/getUser
    app.route('/api/getUser')
        .post(requireApiAuthenticate, 
              function(req, res) {
                  return res.status(200).json( {Hello: req.user.firstname });
              });

    app.route('/api/req')
        .get(requireApiAuthenticate, 
             function(req, res) {
                 res.status(200).json( {req_auth: 'fasdf' } );
             });
   

    // authenticate and generate a token
    app.route('/api/users/login')
        .post(passport.authenticate('api-local-login'), 
              function(req, res) {
                  if (req.isAuthenticated() && req.user) {
                      res.json({token: req.user.rememberme });
                  } else {
                      res.json({error: 'wrong credential'});
                  }
              });

   // Signup
   app.route('/api/users/signup')
      .get(function(req, res) {
         res.render('users/signup', { message: req.flash('signupMessage'), /*csrf: req.csrfToken()*/ });
      })
      .post(passport.authenticate('my-local-signup', {
         successRedirect      : '/home', 
         failureRedirect      : '/users/signup', 
         failureFlash         : true // allow flash messages
      }));




};
